<?php

class auth {
    public function auth() {
        $this->ci =& get_instance();
        $this->ci->load->library('session');
    }

    /**
     * Login user. return error_message jika salah, dan redirect ke hak akses jika benar
     *
     * @param	string (username)
     * @param	string (password)
     * @return	error_message
     **/
    function login($username, $password) {
        $this->ci->load->model('crud/m_member');
        $this->ci->load->model('crud/m_anggota');
        $members = $this->ci->m_member->get("ID_ANGGOTA = ".$this->ci->db->escape($username)." AND ID_MEMBER_TYPE > 1");

        if($members->num_rows() == 0)
            return $this->ci->session->set_flashdata('error', "ID Anggota belum terdaftar, <br/> Silahkan hubungi Koperasi Palapa 85");
        else {
            $anggota = $this->ci->m_anggota->get("ID_ANGGOTA = ".$this->ci->db->escape($username)."AND STATUS = 1");
            $user = $members->first_row();
            $anggota = $anggota->first_row();

            if($user->PASSWORD != md5($password))
                return $this->ci->session->set_flashdata('error', "Password salah, <br/> Silahkan reset password anda dengan menghubungi Koperasi Palapa 85");
            else {
                $this->ci->session->set_userdata(array(
                        'ID_ANGGOTA'	=> $user->ID_ANGGOTA,
                        'USERNAME'	=> $anggota->NAMA_ANGGOTA,
                        'ID_MEMBER_TYPE'=> $user->ID_MEMBER_TYPE
                ));
                redirect();
            }
        }
    }

    /**
     * Is Logged In, check if user masih login atau tidak
     *
     * @param	string(mixed) (redirect url jika belum login)
     * @return	bool
     **/
    function is_logged_in($redirect = NULL, $koperasi_or_toko = 0)
    {
        if($this->ci->session->userdata('ID_ANGGOTA') != "" 
                && ($koperasi_or_toko == 0 || $this->ci->session->userdata("ID_MEMBER_TYPE") == $koperasi_or_toko))
            return TRUE;
        header('Location: '.base_url().$redirect);
        die();
    }
}
?>